package com.lhl.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 同步阻塞IO服务端
 * @author Liu Hanlin
 * @create 2024-10-25 0:30
 */
public class BIOServer {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(8888)) {

            System.out.println("【服务端】等待连接中...");
            while (true){

                // 阻塞等待连接，收到连接后继续执行
                Socket clientSocket = serverSocket.accept();
                System.out.printf("【服务端】收到【客户端：%s】的连接\n", clientSocket.getRemoteSocketAddress());
                handle(clientSocket);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void handle(Socket socket) throws IOException {

        try (InputStream inputStream = socket.getInputStream()) {
            System.out.println("开始处理===");
            byte[] bytes = new byte[1024];
            while ( (inputStream.read(bytes)) != -1){

                System.out.printf("收到【客户端】消息：%s\n", new String(bytes, StandardCharsets.UTF_8));
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
}
